import React, { useState, useEffect } from 'react';
import { Steps as ST, message } from 'antd';
import { usePrevious } from '@umijs/hooks';
import PropTypes from 'prop-types';
import request from '@/utils/request';

const { Step } = ST;

function Steps({ url, method }) {
  const [data, setData] = useState({
    current: 1,
    steps: [
      {
        title: 'First',
        description: '描述信息1',
      },
      {
        title: 'Second',
        description: '描述信息2',
      },
      {
        title: 'Last',
        description: '描述信息3',
      },
    ],
  });

  const preUrl = usePrevious(url);

  const preMethod = usePrevious(method);

  useEffect(() => {
    if ((url !== preUrl || method !== preMethod) && url && method) {
      request(url, { data: { method } }).then(res => {
        const { success, data, errMessage } = res;

        if (success === true) {
          const { current = 0, steps = [] } = data;
          setData({ current, steps });
        }
        message.error(errMessage || '获取数据失败');
      });
    }
  }, [url, method, preUrl, preMethod]);

  return (
    <ST current={data.current}>
      {data.steps.map(item => (
        <Step key={item.title} title={item.title} description={item.description} />
      ))}
    </ST>
  );
}

Steps.defaultProps = {
  method: 'post',
  url: '',
};

Steps.propTypes = {
  url: PropTypes.string,
  method: PropTypes.oneOf(['post', 'get']),
};

export default Steps;
